﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

using log4net;
using Common;
using SysAdmin._01_Config;

namespace SysAdmin._03_Service
{
    public class TimeService
    {
        private static ILog _logger = LogManager.GetLogger(typeof(TimeService));
        private static DateTime _initDateTime;
        private static int _second = 0;
        private static Timer _t = new Timer();

        public static DateTime Now
        {
            get
            {
                return _initDateTime.AddSeconds(_second);
            }
        }

        public static bool Init()
        {
            try
            {
                _t.Elapsed += _t_Elapsed;
                _t.Interval = 1 * 1000;

                string url = string.Format("{0}/Time", MyConfig.WebToolAddr);
                string result = HttpTool.SendGet(url);
                _initDateTime = Convert.ToDateTime(result);
                _t.Start();

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                return false;
            }
        }

        public static void Exit()
        {
            _t.Stop();
            _t.Dispose();
        }

        private static void _t_Elapsed(object sender, ElapsedEventArgs e)
        {
            _second++;
        }
    }
}
